import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { darkTheme } from 'naive-ui'

// 从本地存储加载设置，如果存在
const loadFromStorage = () => {
  try {
    const settings = localStorage.getItem('userSettings')
    return settings ? JSON.parse(settings) : null
  } catch (e) {
    console.error('Failed to load settings from storage:', e)
    return null
  }
}

// 保存设置到本地存储
const saveToStorage = (settings) => {
  try {
    localStorage.setItem('userSettings', JSON.stringify(settings))
  } catch (e) {
    console.error('Failed to save settings to storage:', e)
  }
}

// 检测系统主题偏好
const getSystemTheme = () => {
  return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
    ? 'dark'
    : 'light'
}

// 默认设置
const defaultSettings = {
  theme: 'light', // light, dark, system
  primaryColor: '#2080f0',
  compact: false,
  systemNotify: true,
  emailNotify: false,
  smsNotify: false,
  securityNotify: true
}

// 加载已保存的设置或使用默认设置
const storedSettings = loadFromStorage() || defaultSettings

export const useSettingsStore = defineStore('settings', () => {
  // 用户设置
  const settings = ref(storedSettings)
  
  // 计算是否为暗黑主题 - 考虑系统设置
  const isDarkTheme = computed(() => {
    if (settings.value.theme === 'system') {
      return getSystemTheme() === 'dark'
    }
    return settings.value.theme === 'dark'
  })
  
  // 当前主题对象
  const currentTheme = computed(() => isDarkTheme.value ? darkTheme : null)
  
  // 更新设置
  const updateSettings = (newSettings) => {
    settings.value = { ...settings.value, ...newSettings }
    // 保存到本地存储
    saveToStorage(settings.value)
  }
  
  // 监听系统主题变化
  if (window.matchMedia) {
    window.matchMedia('(prefers-color-scheme: dark)')
      .addEventListener('change', () => {
        // 如果用户选择了跟随系统，则自动更新主题
        if (settings.value.theme === 'system') {
          // 不需要额外更新，因为isDarkTheme是一个computed
          // 会根据系统变化自动更新
        }
      })
  }
  
  return {
    settings,
    isDarkTheme,
    currentTheme,
    updateSettings
  }
}) 